package com.qf.talk.service.impl;

import com.qf.base.utils.PropertiesUtil;
import com.qf.talk.dao.*;
import com.qf.talk.model.*;
import com.qf.talk.service.FriendService;
import com.qf.talk.settings.FriendPolicySetting;
import com.qf.talk.vo.FriendRequestAddVO;
import com.qf.talk.vo.PolicyVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 30909
 */
@Service
public class FriendServiceImpl implements FriendService {

    @Resource
    private FriendBaseDao friendBaseDao;
    /**
     * 好友分组
     */
    @Resource
    private FriendGroupDao friendGroupDao;
    /**
     * 好友申请模式 1、2、3、4、5
     */
    @Resource
    private FriendShipPolicyDao friendShipPolicyDao;

    @Resource
    private FriendRelationDao friendRelationDao;
    @Resource
    private FriendRequestAddDao friendRequestAddDao;
    @Resource
    private FriendRequestAddMapper FriendRequestAddMapper;

    /**
     * Transactional 事物
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addFriendBase(Long userId) {
        FriendBase friendBase = new FriendBase();
        friendBase.setUserId(userId);
        friendBase.setFriendSkipPolicyId(1);
        int result = friendBaseDao.insertSelective(friendBase);

        //给好友创建两个默认的分组
        FriendGroup friendGroup = new FriendGroup();
        friendGroup.setName("我的好友");
        friendGroup.setOrderIndex(1);
        friendGroup.setUserId(userId);
        result += friendGroupDao.insertSelective(friendGroup);

        //黑名单
        friendGroup.setName("黑名单");
        friendGroup.setOrderIndex(99);
        result += friendGroupDao.insertSelective(friendGroup);

        return result;
    }

    @Override
    public List<PolicyVO> selectPolicies() {
        //TODO  下名字错了
        List<FriendShipPolicy> friendSkipPolicies = friendShipPolicyDao.selectByExample(null);
        List<PolicyVO> result = new ArrayList<>();

        for (int i = 0; i < friendSkipPolicies.size(); i++) {
            PolicyVO policyVO = new PolicyVO();
            PropertiesUtil.copyWithAnnotation(friendSkipPolicies.get(i), policyVO);
            result.add(policyVO);
        }
        return result;
    }

    @Override
    public int updatePolicyById(Long userId, Integer policyId, String question, String answer, String password) {

        FriendBaseExample example = new FriendBaseExample();
        FriendBaseExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        //写入数据对象
        FriendBase friendBase = new FriendBase();
        friendBase.setUserId(userId);

        //写入数据结合的 policyId 的取值，多种情况
        if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_1)) {
            friendBase.setFriendSkipPolicyId(1);
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_2)) {
            //写入问题和答案
            friendBase.setFriendSkipPolicyId(2);
            friendBase.setFriendPolicyQuestion(question);
            friendBase.setFriendPolicyAnswer(answer);
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_3)) {
            //写入密码
            friendBase.setFriendSkipPolicyId(3);
            friendBase.setFirendPolicyPassword(password);
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_4)) {
            friendBase.setFriendSkipPolicyId(4);
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_5)) {
            friendBase.setFriendSkipPolicyId(5);
        }
        ///查询
        return friendBaseDao.updateByExampleSelective(friendBase, example);
    }


    @Override
    public int addFriend(Long userId, Long wantId, String message, Long groupId) {
        //组必须存在
        //校验groupId的正确性
        FriendGroup friendGroup = friendGroupDao.selectByPrimaryKey(groupId);
        if (friendGroup == null) {
            //组不存在
            return 0;
        } else {
            if (!friendGroup.getUserId().equals(userId)) {
                //组不属于当前用户
                return 0;
            }
        }
        //wantId 的好友策略不同，处理逻辑也不同
        //所以现重新 wantId 对应的用户好友策略
        FriendBaseExample friendBaseExample = new FriendBaseExample();
        FriendBaseExample.Criteria criteria = friendBaseExample.createCriteria();
        //查找 id 为 wantId的用户
        criteria.andUserIdEqualTo(wantId);
        List<FriendBase> friendBases = friendBaseDao.selectByExample(friendBaseExample);
        if (friendBases == null || friendBases.size() > 0) {
            //目标用户不存在
            return 0;
        }
        FriendBase friendBase = new FriendBase();
        Integer policyId = friendBase.getFriendSkipPolicyId();
        //检验是否成功的标志位
        int result = 0;
        if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_1)) {
            //随意添加
            result = 1;
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_2)) {
            //验证问题
            if (friendBase.getFriendPolicyAnswer().equals(message)) {
                result = 1;
            } else {
                result = 0;
            }
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_3)) {
            //验证密码
            if (friendBase.getFirendPolicyPassword().equals(message)) {
                result = 1;
            } else {
                result = 0;
            }
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_4)) {
            //暂不实现
            return 0;
        } else if (policyId == FriendPolicySetting.policyId(FriendPolicySetting.POLICY_DESC_5)) {
            //拒绝所有人添加
            return 0;
        } else {
            //policyId 有问题
            return 0;
        }
        //只要result ==1 就说明验证通过了
        if (result == 1) {
            //修改数据库，添加好友关系
            //添加好友是双向关系
            //所以对于张三加李四来说
            //应该是两个insert
            FriendRelation friendRelation = new FriendRelation();
            // userId  与 wantId 的好友关系
            //先 select 查询
            FriendRelationExample friendRelationExample = new FriendRelationExample();
            FriendRelationExample.Criteria friendRelationExampleCriteria = friendRelationExample.createCriteria();
            friendRelationExampleCriteria.andUserIdEqualTo(userId);
            friendRelationExampleCriteria.andFriendIdEqualTo(wantId);
            List<FriendRelation> friendRelations = friendRelationDao.selectByExample(friendRelationExample);

            // 在insert
            if (friendRelations == null || friendRelations.size() > 0) {
                //  真？
                friendRelation.setUserId(userId);
                friendRelation.setFriendId(wantId);
                friendRelation.setFirendGruopId(groupId);
                friendRelationDao.insertSelective(friendRelation);
            }

            //wantId 与 userId 的关系
            //先 select
            friendRelationExample = new FriendRelationExample();
            friendRelationExampleCriteria = friendRelationExample.createCriteria();
            friendRelationExampleCriteria.andUserIdEqualTo(wantId);
            friendRelationExampleCriteria.andFriendIdEqualTo(userId);
            friendRelations = friendRelationDao.selectByExample(friendRelationExample);

            //在 insert
            if (friendRelations == null || friendRelations.size() == 0) {
                // 真的 insert
                friendRelation.setUserId(wantId);
                friendRelation.setFriendId(userId);
                //用改分到 wantId 用户的 "我的好友" 哪个组
                // 根据 wantId 与 "我的好友"   查询一个组

                FriendGroupExample friendGroupExample = new FriendGroupExample();
                FriendGroupExample.Criteria friendGroupExampleCriteria = friendGroupExample.createCriteria();
                friendGroupExampleCriteria.andUserIdEqualTo(wantId);
                friendGroupExampleCriteria.andNameEqualTo("我的好友");
                List<FriendGroup> friendGroups = friendGroupDao.selectByExample(friendGroupExample);
                friendRelation.setFirendGruopId(friendGroups.get(0).getId());
                friendRelationDao.insertSelective(friendRelation);
            }

        }

        return result;
    }

    @Override
    public Long askRequest(Long id, Integer state, Long userId, Long groupId) {
        //1、根据主键查询userId 与 reqeustId
        FriendRequestAdd friendRequestAdd = friendRequestAddDao.selectByPrimaryKey(id);
        //这里
        if (friendRequestAdd == null || !userId.equals(friendRequestAdd.getWantId())) {
            return null;
            //数据有问题，当前用户无权、同意或者拒绝 这个请求
        }

        //2、把所有的UserID 请求requestId 的数据全部查询出来
        FriendRequestAddExample example = new FriendRequestAddExample();
        FriendRequestAddExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(friendRequestAdd.getUserId());
        criteria.andWantIdEqualTo(friendRequestAdd.getWantId());
        //3、 根据上述条件过滤出这些记录的state都只为参数 @param state
        FriendRequestAdd fra = new FriendRequestAdd();
        fra.setStart(state);
        //4、当诺 state == 1 就是同意给双向的好友添加好友的关系
        if (state == 1) {
            //修改数据库，添加好友关系
            example.setOrderByClause("create_time desc");
            List<FriendRequestAdd> friendRequestAdds = friendRequestAddDao.selectByExample(example);
            if (friendRequestAdds != null && friendRequestAdds.size() > 0) {
                Long groupIdForUserId = friendRequestAdds.get(0).getGroupId();
                FriendRelation friendRelation = new FriendRelation();
                //添加好友 userId 与  wantId
                //先查后加

                FriendRelationExample friendRelationExample = new FriendRelationExample();
                FriendRelationExample.Criteria friendRelationExampleCriteria = friendRelationExample.createCriteria();
                friendRelationExampleCriteria.andUserIdEqualTo(friendRequestAdd.getUserId());
                friendRelationExampleCriteria.andFriendIdEqualTo(friendRequestAdd.getWantId());
                List<FriendRelation> friendRelations = friendRelationDao.selectByExample(friendRelationExample);
                //再insert
                if (friendRelations == null || friendRelations.size() == 0) {
                    //真的insert
                    friendRelation.setUserId(friendRequestAdd.getUserId());
                    friendRelation.setFriendId(friendRequestAdd.getWantId());
                    friendRelation.setFirendGruopId(groupIdForUserId);
                    friendRelationDao.insertSelective(friendRelation);
                }
                //wantId与userId的好友关系
                //先select
                friendRelationExample = new FriendRelationExample();
                friendRelationExampleCriteria = friendRelationExample.createCriteria();
                friendRelationExampleCriteria.andUserIdEqualTo(friendRequestAdd.getWantId());
                friendRelationExampleCriteria.andFriendIdEqualTo(friendRequestAdd.getUserId());
                friendRelations = friendRelationDao.selectByExample(friendRelationExample);

                //再insert
                if (friendRelations == null || friendRelations.size() == 0) {
                    //真的insert
                    friendRelation.setFriendId(userId);
                    friendRelation.setUserId(friendRequestAdd.getUserId());
                    friendRelation.setFriendId(groupIdForUserId);
                    friendRelationDao.insertSelective(friendRelation);
                }
                //添加wantId与userId的好友关系
                //先查后加

                return friendRequestAdd.getUserId();


            }
        }
        return null;
    }

    @Override
    public List<FriendRequestAddVO> selectRequestByPage(Long userId, Integer lastItemId, Integer pageSize) {
        List<FriendRequestAddVO> list = null;
        if (lastItemId == null) {
            //查第一页
            list = FriendRequestAddMapper.selectRequestPageFirst(userId, pageSize);
        } else {
            //查询其他页
            list = FriendRequestAddMapper.selectRequestPage(userId, lastItemId, pageSize);
        }
        //返回前端list 数据
        return list;
    }


}
